package com.ningxun.rms.web.controller.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.InputStreamResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDate;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Stream;


@RestController
@RequestMapping()
@Slf4j
public class DownloadController {

    @Value("${rms.docFilePath}")
    private String docFilePath;
    @Value("${rms.profile}")
    private String baseUploadDir;

    @PostMapping("/upload")
    public ResponseEntity<Map<String, String>> uploadFile(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            Map<String, String> response = new HashMap<>();
            response.put("message", "请选择一个文件上传。");
            return ResponseEntity.badRequest().body(response);
        }

        if (!"application/pdf".equals(file.getContentType())) {
            Map<String, String> response = new HashMap<>();
            response.put("message", "只允许上传 PDF 格式的文件。");
            return ResponseEntity.badRequest().body(response);
        }

        try {

            //获取年/月/日结构的当前日期
            LocalDate today = LocalDate.now();
            String year = String.valueOf(today.getYear());
            String month = String.format("%02d", today.getMonthValue());
            String day = String.format("%02d", today.getDayOfMonth());

            Path dailyUploadPath = Paths.get(baseUploadDir, year, month, day);

            //创建不存在的目录
            Files.createDirectories(dailyUploadPath);

            String originalFilename = file.getOriginalFilename();
            String nameWithoutExtension = "";
            String fileExtension = "";
            int dotIndex = originalFilename.lastIndexOf('.');
            if (dotIndex > 0 && dotIndex < originalFilename.length() - 1) {
                nameWithoutExtension = originalFilename.substring(0, dotIndex);
                fileExtension = originalFilename.substring(dotIndex + 1);
            } else {
                nameWithoutExtension = originalFilename; // 没有扩展或无效的点位置
            }

            //查找下一个可用的序列号
            int nextSequence = 1;
            Pattern pattern = Pattern.compile(Pattern.quote(nameWithoutExtension) + "(\\d{5})\\." + Pattern.quote(fileExtension));

            try (Stream<Path> stream = Files.list(dailyUploadPath)) {
                Optional<Integer> maxSequence = stream
                        .filter(p -> Files.isRegularFile(p))
                        .map(p -> p.getFileName().toString())
                        .map(fName -> { // 将参数名称更改为fName，以避免与外部作用域filename混淆
                            Matcher matcher = pattern.matcher(fName);
                            if (matcher.matches()) {
                                return Integer.parseInt(matcher.group(1));
                            }
                            return 0; //非匹配文件，将max计算视为0
                        })
                        .filter(seq -> seq > 0) // Only consider valid sequences
                        .max(Comparator.naturalOrder());

                if (maxSequence.isPresent()) {
                    nextSequence = maxSequence.get() + 1;
                }
            }
            long l = System.currentTimeMillis();
            String s = String.valueOf(l);
            String newFileName = String.format("%s%s.%s", nameWithoutExtension,s, fileExtension);
            Path targetFilePath = dailyUploadPath.resolve(newFileName);

            file.transferTo(targetFilePath.toFile());

            //构造下载的相对URL
            String fileUrl = String.format("/profile/upload/%s/%s/%s/%s", year, month, day, newFileName); // New URL format

            Map<String, String> response = new HashMap<>();
            response.put("message", "文件上传成功");
            response.put("filename", newFileName);
            response.put("originalFilename", originalFilename);
            response.put("url", fileUrl);
            return ResponseEntity.ok().body(response);
        } catch (IOException e) {
            log.error("文件上传失败", e);
            Map<String, String> errorResponse = new HashMap<>();
            errorResponse.put("message", "文件上传失败：" + e.getMessage());
            return ResponseEntity.status(500).body(errorResponse);
        }
    }

    //fullPath完整的路径
    @GetMapping("/profile/download")
    public ResponseEntity<Resource> downloadUploadedFile(
            @RequestParam("fullPath") String fullPath) {
        log.info("下载文件: {}", fullPath);
        try {
            // 期望的完整路径：YYYY/MM/DD/filename.pdf（没有@GetMapping本身的斜杠）
            String[] pathSegments = fullPath.split("/");
            if (pathSegments.length < 4) { // Minimum: YYYY/MM/DD/filename
                log.error("下载的fullPath无效： {}", fullPath);
                return ResponseEntity.badRequest().body(null);
            }

            String year = pathSegments[0];
            String month = pathSegments[1];
            String day = pathSegments[2];
            // 如果文件名本身包含斜杠（不太可能但安全），则从剩余段重建文件名。
            String filename = String.join("/", Arrays.copyOfRange(pathSegments, 3, pathSegments.length));

            // 修改为D:/ruoyi/uploadPath
            Path filePath = Paths.get(baseUploadDir, year, month, day, filename);

            if (!Files.exists(filePath)) {
                log.error("找不到文件: {}", filePath.toString());
                return ResponseEntity.notFound().build();
            }

            Resource resource = new InputStreamResource(new FileInputStream(filePath.toFile()));
            long contentLength = Files.size(filePath);
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            // 确保内容处理的文件名编码
            headers.setContentDispositionFormData("attachment", URLEncoder.encode(filename, StandardCharsets.UTF_8.toString()));
            headers.setContentLength(contentLength);

            return ResponseEntity.ok().headers(headers).body(resource);

        } catch (IOException e) {
            log.error("Failed to download uploaded file: {}", fullPath, e);
            return ResponseEntity.status(500).body(null); // Or return an empty body with a 500 status
        }
    }

    @GetMapping("/download/requirement-doc")
    public ResponseEntity<Resource> downloadRequirementDoc() throws IOException {
        Path filePath = Paths.get(docFilePath); //修正了相对于项目根的路径
        if (!Files.exists(filePath)) {
            log.error("找不到文件: {}", filePath.toString());
            return ResponseEntity.notFound().build();
        }
        Resource resource = new InputStreamResource(new FileInputStream(filePath.toFile()));
        long contentLength = Files.size(filePath);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        headers.setContentDispositionFormData("attachment", URLEncoder.encode("青年实干家计划报名表.docx", StandardCharsets.UTF_8.toString()));
        headers.setContentLength(contentLength);

        return ResponseEntity.ok().headers(headers).body(resource);
    }


}
